package org.lc.stk.controller;

import org.lc.stk.model.Department;
import org.lc.stk.service.DepartmentService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/departments")
public class DepartmentController {

    private final DepartmentService departmentService;

    public DepartmentController(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    @GetMapping
    @Secured("ROLE_ADMIN")
    public String listDepartments(Model model) {
        List<Department> departments = departmentService.findAllNonDeleted();
        model.addAttribute("departments", departments);
        return "departments";
    }

    @PostMapping
    @Secured("ROLE_ADMIN")
    @ResponseBody
    public Department createDepartment(@RequestBody Department department) {
        return departmentService.save(department);
    }

    @PutMapping("/{id}")
    @Secured("ROLE_ADMIN")
    @ResponseBody
    public Department updateDepartment(@PathVariable Long id, @RequestBody Department department) {
        department.setId(id);
        return departmentService.save(department);
    }

    @DeleteMapping("/{id}")
    @Secured("ROLE_ADMIN")
    @ResponseBody
    public void deleteDepartment(@PathVariable Long id) {
        departmentService.softDelete(id);
    }
}